package com.cluster.gulimall.product.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import java.io.IOException;


@Configuration
@ConfigurationProperties("spring.redis")
public class RedissonConfig {

    /**
     * 所有对Redisson的使用都是通过RedissonClient
     *
     * @return
     * @throws IOException
     */
//    @Bean(destroyMethod="shutdown")
//    public RedissonClient redisson() throws IOException {
//        //1、创建配置
//        Config config = new Config();
//        config.useSingleServer().setAddress("redis://47.102.44.15:6379");
//        config.useSingleServer().setPassword("000415");
//        //2、根据Config创建出RedissonClient实例
//        //Redis url should start with redis:// or rediss://
//        RedissonClient redissonClient = Redisson.create(config);
//        return redissonClient;
//    }

//    @Value("${spring.redis.addresses}")
//    private String addresses;
    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.port}")
    private String port;

    private int timeout = 3000;
    private int connectionPoolSize = 64;
    private int connectionMinimumIdleSize = 10;
    private int pingConnectionInterval = 60000;
    private static String ADDRESS_PREFIX = "redis://";

    /**
     * 自动装配
     */
    @Bean
    public RedissonClient redisson() {
        Config config = new Config();
        //  判断redis 的host是否为空
        if (StringUtils.isEmpty(host)) {
            throw new RuntimeException("host is  empty");
        }
        //  配置host，port等参数
        config.useSingleServer()
                //redis://127.0.0.1:7181
                .setAddress(ADDRESS_PREFIX + this.host + ":" + port)
                .setTimeout(this.timeout)
                .setPingConnectionInterval(pingConnectionInterval)
                .setConnectionPoolSize(this.connectionPoolSize)
                .setConnectionMinimumIdleSize(this.connectionMinimumIdleSize);
        //  判断进入redis 是否密码
        if (!StringUtils.isEmpty(this.password)) {
            config.useSingleServer().setPassword(this.password);
        }
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }

}
